@using System.Text.RegularExpressions;
@inherits BasePage
@inject NavigationManager NavigationManager

<BootstrapBlazorRoot>
    @if (hasToken == true || IsPublic == true)
    {
        <Router AppAssembly="@typeof(Program).Assembly" OnNavigateAsync="OnNavigateAsync">
            <Found Context="routeData">
                <CascadingValue Value="User" IsFixed="true">
                    <RouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
                </CascadingValue>
            </Found>
            <NotFound>
                <LayoutView Layout="@typeof(EmptyLayout)">
                    <p>Sorry, there's nothing at this address.</p>
                </LayoutView>
            </NotFound>
        </Router>
    }
    else if (hasToken == false)
    {
        <Router AppAssembly="@typeof(Program).Assembly">
            <Found Context="routeData">
                <CascadingValue Value="User" IsFixed="false">
                    <Login @bind-LoginSuccess="hasToken" OnUserInfoSet="async ()=> {User = await GetUserInfo(); }" />
                </CascadingValue>
            </Found>
            <NotFound>
                <LayoutView Layout="@typeof(EmptyLayout)">
                    <p>Sorry, there's nothing at this address.</p>
                </LayoutView>
            </NotFound>
        </Router>
    }
</BootstrapBlazorRoot>

@code {

    private LoginUserInfo User;
    private bool? hasToken { get; set; }
    private bool? IsPublic { get; set; }

    protected override void OnInitialized()
    {
        IsPublicPage();
        base.OnInitialized();
    }

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        await base.OnAfterRenderAsync(firstRender);

        if (firstRender)
        {
            await JSRuntime.InvokeAsync<string>("commonFuncs.loadFinish");
            var token = await GetToken();
            if (string.IsNullOrEmpty(token))
            {
                hasToken = false;
            }
            else
            {
                var refreshtoken = await GetRefreshToken();
                var rv = await WtmBlazor.Api.CallAPI<DynamicData>($"/api/_account/RefreshToken?refreshToken={refreshtoken}", HttpMethodEnum.POST, new { });
                if (rv.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    var t = rv.Data.Fields["access_token"].ToString();
                    var r = rv.Data.Fields["refresh_token"].ToString();
                    await SetToken(t, r);
                    var userinfo = await WtmBlazor.Api.CallAPI<LoginUserInfo>("/api/_account/CheckUserInfo", HttpMethodEnum.GET, new { });

                    if (userinfo.StatusCode == System.Net.HttpStatusCode.OK)
                    {
                        await SetUserInfo(userinfo.Data);
                        User = await GetUserInfo();
                        hasToken = true;
                    }
                    else
                    {
                        //await WtmBlazor.Toast.Error(WtmBlazor.Localizer["Sys.Error"], rv.Errors.Message[0]);
                        hasToken = false;
                    }
                }
                else
                {
                    await DeleteToken();
                    hasToken = false;
                }

            }
            StateHasChanged();
        }
    }

    private void OnNavigateAsync(NavigationContext args)
    {
        IsPublicPage();
        if (args.Path.ToLower().StartsWith("login"))
        {
            NavigationManager.NavigateTo("/");
        }
    }

    private void IsPublicPage()
    {
        var url = NavigationManager.ToBaseRelativePath(NavigationManager.Uri?.ToLower());
        var i =  url.IndexOf('?');
        if(i >= 0)
        {
            url = url[0..i];
        }
        if (this.WtmBlazor.PublicPages.Any(x => Regex.IsMatch(url, x)))
        {
            IsPublic = true;
        }
        else
        {
            IsPublic = false;
        }

    }
}
